<?php

class Nuo_View_Parser
{
	/**
	 * get the block engine to parse content to xhtml
	 * @param array $region
	 * @param array $areas
	 * @return string
	 */
	public function parseRegion($region)
	{
		$areas = array();

		foreach ($region['areas'] as $name => $blocks)
		{
			$areas["{$name}"] = $this -> parseArea($blocks);
		}

		// column
		$method = 'layoutGrid' . Nuo::inflect($region['layout_grid']);

		if (!method_exists($this, $method))
		{
			$method = 'layoutGridSimple';
		}

		return $this -> {$method}($areas, $region);

	}

	/**
	 * render a regions
	 */
	public function parseArea($blocks)
	{
		$xhtml = '';
		foreach ($blocks as $block)
		{
			$xhtml .= '<div class="'. $block['css_class'] .'" id="'. $block['css_id'] .'">'. $this -> parseBlock($block) . '</div>';
		}
		return $xhtml;
	}

	/**
	 * render a block
	 */
	public function parseBlock($block)
	{
		$xhtml = '';
		$cls = $block['block_class'];
		$ele = new $cls();

		$xhtml .= $ele -> dispatch();
		// prepare decorators for block if needed.

		// unset element
		unset($ele);

		return $xhtml;
	}

	/**
	 * parse region none
	 * @param array $areas
	 * @param array $region
	 * @return string xhtml string
	 */
	public function layoutGridSimple($areas, $region)
	{
		$xhtml = '<div class="uiRegion uiRegionNone">';

		$xhtml .= '<div class="uiArea uiAreaMain">' . @$areas['main'] . '</div>';

		$xhtml .= '</div>';

		return $xhtml;
	}

	/**
	 * parse region one left
	 * @param array $areas
	 * @param array $region
	 * @return string xhtml string
	 */
	public function layoutGridOneLeft($areas, $region)
	{
		$hasLeft = isset($areas['column']) && !empty($areas['column']);
		
		$regionClass = $hasLeft ? 'uiRegionOneLeft' : 'uiRegionNone';
		
		/**
		 * xhtml result
		 * @var string
		 */
		$xhtml = '<div class="uiRegion uiRegionOneLeft">';

		if ($hasLeft)
		{
			$xhtml .= '<div class="uiArea uiAreaLeft">' . $areas['column'] . '</div>';
		}
		
		$xhtml .= '<div class="uiArea uiAreaMain">' . @$areas['main'] . '</div>';

		$xhtml .= '</div>';

		return $xhtml;

	}
	
	/**
	 * parse region one left
	 * @param array $areas
	 * @param array $region
	 * @return string xhtml string
	 */
	public function layoutGridOneRight($areas, $region)
	{
		$hasRight = isset($areas['column']) && !empty($areas['column']);
		
		$regionClass = $hasRight ? 'uiRegionOneLeft' : 'uiRegionNone';
		
		/**
		 * xhtml result
		 * @var string
		 */
		$xhtml = '<div class="uiRegion uiRegionOneLeft">';
		
		if ($hasRight)
		{
			$xhtml .= '<div class="uiArea uiAreaRight">' . $areas['column'] . '</div>';
		}
		
		$xhtml .= '<div class="uiArea uiAreaMain">' . $areas['main'] . ' </div>';
		
		

		$xhtml .= '<div style="clear:both"><div></div>';

		return $xhtml;

	}

}
